<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import router from "@/router";
import { getByPageAndStatus } from "../api/orders.js";

const orderList = ref([]);
const currentFilter = ref("全部订单");
const currentPage = ref(1);
const pageSize = 2; // 每页显示两条
const totalOrders = ref(0);
const loading = ref(false);
//从localstorage拿出userid
const userId = Number(localStorage.getItem("userId"))

// 获取订单
async function fetchOrders(orderStatus: string, page: number) {
  loading.value = true;
  try {
    const statusParam = orderStatus === "全部订单" ? "" : orderStatus;
    const res = await getByPageAndStatus(userId, page, statusParam);
    const data = res.data.data;

    orderList.value = data.orders || [];
    totalOrders.value = data.total;
    currentPage.value = page;
    currentFilter.value = orderStatus; // 更新当前筛选状态
  } finally {
    loading.value = false;
  }
}

function byPageAndStatus(orderStatus: string) {
  currentFilter.value = orderStatus; // 更新 filter
  fetchOrders(orderStatus, 1);       // 从第一页请求
}

function handlePageChange(page: number) {
  fetchOrders(currentFilter.value, page);
}


//前端二次分页了，不需要，
// const pagedOrders = computed(() => {
//   const start = (currentPage.value - 1) * pageSize;
//   return orderList.value.slice(start, start + pageSize);
// });

watch(currentPage, (newPage) => window.scrollTo(0, 0));

onMounted(() => fetchOrders("全部订单"));


// 点击酒店跳转
const toHotelDetail = (hotelId) => {
  router.push(`hDetail/${hotelId}`)
}
function toOrderDetail(id: number) {
  router.push(`/orderDetail/${id}`);
}
</script>

<template>
  <div class="order-container">
    <!-- 顶部筛选按钮 -->
    <div class="filter-btns">
      <button
        :class="['filter-btn', { active: currentFilter === '全部订单' }]"
        @click="byPageAndStatus('全部订单')"
      >
        全部订单
      </button>
      <button
        :class="['filter-btn', { active: currentFilter === '待入住' }]"
        @click="byPageAndStatus('待入住')"
      >
        待入住
      </button>
      <button
        :class="['filter-btn', { active: currentFilter === '待支付' }]"
        @click="byPageAndStatus('待支付')"
      >
        待支付
      </button>
      <!-- 已入住/已完成/已取消 -->
      <button
        :class="['filter-btn', { active: currentFilter === '已入住' }]"
        @click="byPageAndStatus('已入住')"
      >
        已入住
      </button>
      <button
        :class="['filter-btn', { active: currentFilter === '已完成' }]"
        @click="byPageAndStatus('已完成')"
      >
        已完成
      </button>
      <button
        :class="['filter-btn', { active: currentFilter === '已取消' }]"
        @click="byPageAndStatus('已取消')"
      >
        已取消
      </button>
    </div>

    <div v-if="loading" class="loading">加载中...</div>

    <div v-else class="order-page">
      <!-- 订单列表 + 空白撑开 -->
      <div class="order-list-wrapper">
        <div v-if="orderList.length > 0" class="order-list">
          <div
            v-for="order in orderList"
            :key="order.orderId"
            class="order-card"
          >
            <div class="order-info">
              <h3 class="hotel-name">{{ order.hotelName }}</h3>
              <p class="address">📍 {{ order.hotelAddress }}</p>
              <p>入住日期：{{ order.checkIn }} 至 {{ order.checkOut }}</p>
              <p>入住人：{{ order.userName }}</p>
              <p class="detail">{{ order.roomtypeName }}（{{ order.roomArea }}）</p>
            </div>
            <div class="order-side">
              <p
                class="status"
                :class="{
                  completed: order.orderStatus === '已完成',
                  upcoming: order.orderStatus === '待入住',
                  pending: order.orderStatus === '待支付',
                  cancelled: order.orderStatus === '已取消',
                  checkedin: order.orderStatus === '已入住'
                }"
              >
                {{ order.orderStatus }}
              </p>
              <p class="price">￥{{ order.orderPrice ?? order.roomtypePrice }}</p>
              <!-- <p class="comment" v-if="order.isComment !== undefined">
                {{ order.isComment === 1 ? '已评价' : '未评价' }}
              </p> -->
              <button class="detail-btn" @click="toHotelDetail(order.hotelId)">酒店详情</button>
              <button class="detail-btn" @click="toOrderDetail(order.orderId)">订单详情</button>
            </div>
          </div>
        </div>
        <p v-else class="empty">暂无订单</p>
      </div>

      <!-- 分页固定在订单列表容器底部 -->
    <el-pagination
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="totalOrders"
      v-model:current-page="currentPage"
      @current-change="handlePageChange"
    />

    </div>
  </div>
</template>

<style scoped>
.order-container {
  max-width: 800px;
  margin: 0 auto;
}

/* 筛选按钮 */
.filter-btns {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin: 20px 0;
}

.filter-btn {
  padding: 8px 18px;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  background: #fff;
  cursor: pointer;
  transition: 0.3s;
  font-size: 14px;
}
.filter-btn:hover { background: #f2f6fc; }
.filter-btn.active { background: #409eff; color: white; border-color: #409eff; }

/* 订单区域 */
.order-page {
  position: relative;        /* 分页条绝对定位参考 */
  min-height: 300px;         /* 保证分页条在底部 */
}

/* 订单列表包裹器撑开剩余空间 */
.order-list-wrapper {
  padding-bottom: 60px;      /* 留出分页条高度 */
  display: flex;
  flex-direction: column;
  min-height: 200px;         /* 可以根据需要调整 */
}

.order-list {
  display: flex;
  flex-direction: column;
}

/* 单个订单卡片 */
.order-card {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  border: 1px solid #eee;
  border-radius: 12px;
  padding: 16px 20px;
  margin-bottom: 20px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.order-info { flex: 1; }
.order-side {
  text-align: right;
  min-width: 120px;
  margin-left: 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

/* 分页条固定在订单列表底部 */
.pagination {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 1px solid #eee;
  background: #fff;
  padding-bottom: 5px;
}

.status { font-size: 14px; font-weight: bold; }
.status.completed { color: #4caf50; }
.status.upcoming { color: #409eff; }
.status.pending { color: #e6a23c; }
.status.cancelled { color: #f56c6c; }
.status.checkedin { color: #67c23a; }

.price { font-size: 20px; font-weight: bold; color: #ff6600; }
.detail-btn {
  width: 100px; padding: 6px 14px; border: none; border-radius: 6px;
  background: #409eff; color: white; cursor: pointer; transition: 0.3s;
}
.detail-btn:hover { background: #66b1ff; }

.loading, .empty { text-align: center; color: #999; margin-top: 40px; }
.comment { font-size: 12px; color: #409eff; }
</style>
